package com.lagou.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.OSSObject;
import com.google.common.collect.Sets;
import com.lagou.config.OssConfiguration;
import com.lagou.model.UploadResult;
import com.lagou.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Set;
import java.util.UUID;

/**
 * 阿里云文件系统实现
 */
@Service
public class AliyunOssFileServiceImpl implements FileService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOssFileServiceImpl.class.getName());

    /**
     * 限制上传文件类型
     */
    private static final Set<String> LIMIT_FILE_TYPE_SET = Sets.newHashSet("image/jpg", "image/jpeg", "image/png");

    /**
     * 限制文件容量，单位：byte
     */
    private static final long LIMIT_FILE_SIZE = 5242880L;

    @Autowired
    private OssConfiguration ossConfiguration;

    @Autowired
    private OSSClient ossClient;

    @Override
    public UploadResult upload(MultipartFile multipartFile) throws IOException {
        String contentType = multipartFile.getContentType();
        if (!LIMIT_FILE_TYPE_SET.contains(contentType)) {
            return new UploadResult(false, "不支持上传的文件类型");
        }

        long fileSize = multipartFile.getSize();
        if (fileSize > LIMIT_FILE_SIZE) {
            return new UploadResult(false, "文件不得大于5M");
        }

        String fileName = generateFileName(multipartFile.getOriginalFilename());
        ossClient.putObject(ossConfiguration.getBucketName(), fileName, multipartFile.getInputStream());

        UploadResult uploadResult = new UploadResult();
        uploadResult.setFilePath(ossConfiguration.getUrlPrefix() + fileName);
        uploadResult.setFileName(fileName);
        return uploadResult;
    }

    @Override
    public void download(String fileName, OutputStream outputStream) throws IOException {
        if (!ossClient.doesObjectExist(ossConfiguration.getBucketName(), fileName)) {
            return;
        }

        OSSObject ossObject = ossClient.getObject(ossConfiguration.getBucketName(), fileName);
        ResponseMessage response = ossObject.getResponse();
        if(HttpStatus.SC_OK != response.getStatusCode()) {
            return;
        }

        byte[] byteArray = new byte[1024 * 1024];
        InputStream inputStream = ossObject.getObjectContent();
        int size = 0;
        while((size = inputStream.read(byteArray)) != -1) {
            outputStream.write(byteArray, 0, size);
        }

        inputStream.close();
    }

    @Override
    public void delete(String fileName) {
        ossClient.deleteObject(ossConfiguration.getBucketName(), fileName);
    }

    /**
     * 生成文件名称
     *
     * @return
     */
    private String generateFileName(String originalFileName) {
        DateTime dateTime = new DateTime();
        return dateTime.getYear() + "/" + dateTime.getMonthOfYear() + "/"
                + dateTime.getDayOfMonth() + "/" + dateTime.getHourOfDay()
                + "/" + dateTime.getMinuteOfHour() + "-" + dateTime.getSecondOfMinute()
                + "-" + UUID.randomUUID().toString().replace("-", "")
                + "." + StringUtils.substringAfterLast(originalFileName, ".");
    }

}
